package com.neusoft.NEPS.controller;

import com.neusoft.NEPS.common.AlertUtils;
import com.neusoft.NEPS.entity.User;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import static com.neusoft.NEPS.common.FXMLUtils.switchToShow;
import static com.neusoft.NEPS.common.FileUtils.readMapObject;

public class UserLoginViewController {

    @FXML
    private Hyperlink link_register;

    @FXML
    private Button btn_login;

    @FXML
    private TextField txt_phoneNumber;

    @FXML
    private PasswordField txt_password;

    @FXML
    public void register() {
        try {
            switchToShow(link_register, "UserRegisterView.fxml");
        } catch (IOException e) {
            e.printStackTrace();
            AlertUtils.showDialog(null, "界面加载失败。");
        }
    }

    @FXML
    public void login() {
        String phoneNumber = txt_phoneNumber.getText();
        String password = txt_password.getText();

        if (phoneNumber.isEmpty() || password.isEmpty()) {
            AlertUtils.showDialog(null, "手机号或密码不能为空。");
            return;
        }

        User u0 = new User(phoneNumber, password);
        try {
            File file = new File("user.txt");
            if (!file.exists() || file.length() == 0) {
                AlertUtils.showDialog(null, "登录失败，用户名或密码错误。");
                return;
            }

            Map<String, User> userMap = readMapObject("user.txt");

            if (userMap.containsKey(u0.getPhoneNumber()) && u0.equals(userMap.get(u0.getPhoneNumber()))) {
                AlertUtils.showDialog(null, "登录成功！");
                switchToShow(btn_login, "FeedbackView.fxml");
            } else {
                AlertUtils.showDialog(null, "登录失败，用户名或密码错误。");
            }
        } catch (IOException e) {
            e.printStackTrace();
            AlertUtils.showDialog(null, "登录时发生错误。");
        }
    }
}